package oracle.apps.financials.collection.widget;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.widget.Toast;

public abstract class LoadingDialog<Input, Result> extends AsyncTask<Input, WSError, Result> {

	private ProgressDialog mProgressDialog;
	protected Activity mActivity;
	private int loadingMessage;
	private int failMessage;
	private boolean isShowDialog = true;

	public LoadingDialog(Activity activity, int loadingMsg, int failMsg) {
		this.mActivity = activity;
		this.loadingMessage = loadingMsg;
		this.failMessage = failMsg;
	}

	@Override
	public void onCancelled() {
		failMsg();
		super.onCancelled();
	}

	@Override
	public void onPreExecute() {
		if (this.isShowDialog) {
			showProgressDialog();
		}
		super.onPreExecute();
	}

	public void showProgressDialog() {
		String title = "";
		String message = mActivity.getString(loadingMessage);

		mProgressDialog = ProgressDialog.show(mActivity, title, message, true, true, new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialogInterface) {
				LoadingDialog.this.cancel(true);
			}

		});
	}

	@Override
	public abstract Result doInBackground(Input... params);

	@Override
	public void onPostExecute(Result result) {
		super.onPostExecute(result);
		if (this.isShowDialog) {
			dismissProcessDialog();

		}

		if (result != null) {
			doStuffWithResult(result);
		} else {
			failMsg();
		}
	}

	public void dismissProcessDialog() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
	}

	protected void failMsg() {
		Toast.makeText(mActivity, failMessage, 2000).show();
	}

	/**
	 * Very abstract function hopefully very meaningful name, executed when
	 * result is other than null
	 * 
	 * @param result
	 * @return
	 */
	public abstract void doStuffWithResult(Result result);

	@Override
	protected void onProgressUpdate(WSError... values) {
		Toast.makeText(mActivity, values[0].getMessage(), Toast.LENGTH_LONG).show();
		this.cancel(true);
		dismissProcessDialog();
		super.onProgressUpdate(values);
	}

	public int getLoadingMessage() {
		return loadingMessage;
	}

	public void setLoadingMessage(int loadingMessage) {
		this.loadingMessage = loadingMessage;
	}

	public int getFailMsg() {
		return failMessage;
	}

	public void setfailMessage(int failMessage) {
		this.failMessage = failMessage;
	}

	public boolean isShowDialog() {
		return isShowDialog;
	}

	public void setShowDialog(boolean isShowDialog) {
		this.isShowDialog = isShowDialog;
	}

}
